package com.laker.admin.module.ext.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.laker.admin.framework.aop.metrics.Metrics;
import com.laker.admin.framework.aop.trace.TraceCodeBlock;
import com.laker.admin.framework.model.PageResponse;
import com.laker.admin.framework.model.Response;
import com.laker.admin.module.ext.controller.params.TXmglKhxxLxrSUParam;
import com.laker.admin.module.ext.controller.params.TXmglKhxxPageParam;
import com.laker.admin.module.ext.controller.params.TXmglKhxxSUParam;
import com.laker.admin.module.ext.entity.XmglKhxxDO;
import com.laker.admin.module.ext.entity.XmglKhxxLxrDO;
import com.laker.admin.module.ext.service.IXmglKhxxLxrService;
import com.laker.admin.module.ext.service.IXmglKhxxService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 项目管理-客户信息
 *
 * @author zhangqingshan
 * @date 2025-03-11
 */
@RestController
@RequestMapping("/ext/xmgl_khxx")
@Metrics
public class XmglKhxxController {

    @Autowired
    private IXmglKhxxService xmglKhxxService;

    @Autowired
    private IXmglKhxxLxrService xmglKhxxLxrService;

    /**
     * 新增/修改客户信息
     * 传id的代表修改，不传代表新增,可连带新增或修改联系人或维护人,权限：khxx.edit
     *
     * @param param
     * @return {@link Response }
     */
    @PostMapping
    @SaCheckPermission("khxx.edit")
    @Transactional(rollbackFor = Exception.class)
    public Response saveOrUpdate(@RequestBody @Validated TXmglKhxxSUParam param) {
        if (StringUtils.isBlank(param.getKehumingcheng()) && param.getId() == null) {
            return Response.error("新增客户，客户名称不能为空");
        }
        XmglKhxxDO xmglKhxxDO = new XmglKhxxDO();
        xmglKhxxDO.setId(param.getId());
        xmglKhxxDO.setKehumingcheng(param.getKehumingcheng());
        xmglKhxxDO.setKehuleixing(param.getKehuleixing());
        xmglKhxxDO.setKehujibie(param.getKehujibie());
        xmglKhxxDO.setDizhiquyucengji(param.getDizhiquyucengji());
        xmglKhxxDO.setDizhixiangxidizhi(param.getDizhixiangxidizhi());
        xmglKhxxDO.setBeizhu(param.getBeizhu());
        xmglKhxxDO.setFujian(param.getFujian());

        if (xmglKhxxService.saveOrUpdate(xmglKhxxDO) && param.getKhLxrList() != null) {
            param.getKhLxrList().forEach(p -> {
                XmglKhxxLxrDO xmglKhxxLxrDO = new XmglKhxxLxrDO();
                xmglKhxxLxrDO.setId(p.getId());
                xmglKhxxLxrDO.setType(p.getType());
                xmglKhxxLxrDO.setDiyi(p.getDiyi());
                xmglKhxxLxrDO.setXingming(p.getXingming());
                xmglKhxxLxrDO.setJiaose(p.getJiaose());
                xmglKhxxLxrDO.setDianhua(p.getDianhua());
                xmglKhxxLxrDO.setYoujian(p.getYoujian());
                xmglKhxxLxrDO.setKhxx_id(xmglKhxxDO.getId());
                xmglKhxxLxrService.saveOrUpdate(xmglKhxxLxrDO);
            });
        }
        return Response.ok();
    }

    /**
     * 新增/修改联系人或负责人
     * 单个修改，传id的代表修改，不传代表新增,权限：khxx.edit
     * @param param
     * @param khxxId KHXX 编号
     * @return {@link Response }
     */
    @PostMapping("/lxrOrWfr")
    @SaCheckPermission("khxx.edit")
    @Transactional(rollbackFor = Exception.class)
    public Response saveOrUpdateLxr(@RequestBody @Validated TXmglKhxxLxrSUParam param,Long khxxId) {
        if (StringUtils.isBlank(param.getXingming()) && param.getId() == null) {
            return Response.error("新增联系人或负责人，姓名不能为空");
        }
        XmglKhxxLxrDO xmglKhxxLxrDO = new XmglKhxxLxrDO();
        xmglKhxxLxrDO.setId(param.getId());
        xmglKhxxLxrDO.setType(param.getType());
        xmglKhxxLxrDO.setDiyi(param.getDiyi());
        xmglKhxxLxrDO.setXingming(param.getXingming());
        xmglKhxxLxrDO.setJiaose(param.getJiaose());
        xmglKhxxLxrDO.setDianhua(param.getDianhua());
        xmglKhxxLxrDO.setYoujian(param.getYoujian());
        xmglKhxxLxrDO.setKhxx_id(khxxId);
        xmglKhxxLxrService.saveOrUpdate(xmglKhxxLxrDO);

        return Response.ok();
    }

    /**
     * 删除客户信息
     * 逻辑删除，权限：khxx.del
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("khxx.del")
    @Transactional(rollbackFor = Exception.class)
    public Response deleteKhxx(@PathVariable("id") Long id) {
        xmglKhxxService.update(Wrappers.lambdaUpdate(XmglKhxxDO.class).set(XmglKhxxDO::getIsDel, true).eq(XmglKhxxDO::getId, id));
        return Response.ok();
    }

    /**
     * 删除联系人或维护人
     * 物理删除，权限：khxx.del
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @DeleteMapping("/lxr/{id}")
    @SaCheckPermission("khxx.del")
    @Transactional(rollbackFor = Exception.class)
    public Response deleteKhxxLxr(@PathVariable("id") Long id) {
        xmglKhxxLxrService.removeById(id) ;
        return Response.ok();
    }

    /**
     * 单个获取客户信息
     * 权限：khxx.list
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @GetMapping("/{id}")
    @SaCheckPermission("khxx.list")
    public Response getKhxx(@PathVariable("id") Long id){
        XmglKhxxDO byId = xmglKhxxService.getById(id);
        if (byId != null){
            byId.setLxrList(xmglKhxxLxrService.list(Wrappers.lambdaQuery(XmglKhxxLxrDO.class).eq(XmglKhxxLxrDO::getKhxx_id,id)));
        }
        return Response.ok(byId);
    }

    /**
     * 单个获取联系人或维护人
     *
     *
     * @param id 身份证
     * @return {@link Response }
     */
    @GetMapping("/lxr/{id}")
    @SaCheckPermission("khxx.list")
    public Response getKhxxLxr(@PathVariable("id") Long id){
        return Response.ok(xmglKhxxLxrService.getById(id));
    }

    /**
     * 分页查询客户信息
     * 权限：khxx.list
     * @param param
     * @return {@link PageResponse }
     */
    @PostMapping("/page")
    @SaCheckPermission("khxx.list")
    public PageResponse get(@RequestBody TXmglKhxxPageParam param){
        Page page = param.toPage();
        LambdaQueryWrapper<XmglKhxxDO> queryWrapper = Wrappers.lambdaQuery(XmglKhxxDO.class)
                .eq(XmglKhxxDO::getIsDel, false)
                .like(StringUtils.isNotBlank(param.getKehumingcheng()), XmglKhxxDO::getKehumingcheng, param.getKehumingcheng())
                .eq(StringUtils.isNotBlank(param.getKehuleixing()), XmglKhxxDO::getKehuleixing, param.getKehuleixing())
                .eq(StringUtils.isNotBlank(param.getKehujibie()), XmglKhxxDO::getKehujibie, param.getKehujibie())
                .eq(param.getCreateBy() != null, XmglKhxxDO::getCreateBy, param.getCreateBy());
        if (StringUtils.isNotBlank(param.getFzr())){
            List<XmglKhxxLxrDO> list = xmglKhxxLxrService.list(Wrappers.lambdaQuery(XmglKhxxLxrDO.class)
                    .like(XmglKhxxLxrDO::getXingming, param.getFzr()));
            if (list != null && list.size() > 0){
                queryWrapper.in(XmglKhxxDO::getId, list.stream().map(XmglKhxxLxrDO::getKhxx_id).collect(Collectors.toList()));
            }
        }
        queryWrapper.orderByDesc(StringUtils.isBlank(param.getOrderBy()), XmglKhxxDO::getCreateTime) ;

        IPage<XmglKhxxDO> pageList = TraceCodeBlock.trace("xmglKhxxService.page",
                () -> xmglKhxxService.page(page, queryWrapper));
        pageList.getRecords().forEach(p -> {
            p.setLxrList(xmglKhxxLxrService.list(Wrappers.lambdaQuery(XmglKhxxLxrDO.class).eq(XmglKhxxLxrDO::getKhxx_id, p.getId())));
        });

        return PageResponse.ok(pageList.getRecords(),pageList.getTotal());
    }

}
